const tbody = document.querySelector("tbody");

async function getScore() {
  const result = await axios({ url: "/score/list" });
  console.log(result);
  const data = result.data.data;
  let html = ``;
  //================渲染
  for (const key in data) {
    html += `
    <tr>
    <th scope="row">${key}</th>
    <td>${data[key].name}</td>
    <td class="score" data-id="${key}" data-batch="${1}">${
      data[key].score[0]
    }</td>
    <td class="score" data-id="${key}" data-batch="${2}">${
      data[key].score[1]
    }</td>
    <td class="score" data-id="${key}" data-batch="${3}">${
      data[key].score[2]
    }</td>
    <td class="score" data-id="${key}" data-batch="${4}">${
      data[key].score[3]
    }</td>
    <td class="score" data-id="${key}" data-batch="${5}">${
      data[key].score[4]
    }</td>
  </tr>
    `;
  }
  tbody.innerHTML = html;
}
getScore();
//===================修改成绩
//绑定鼠标双击事件
tbody.addEventListener("dblclick", function (e) {
  //判断双击的是不是成绩
  if (e.target.classList.contains("score")) {
    console.log(123);
    //创建一个input 标签
    const input = document.createElement("input");
    input.type = "text";
    //双击时 让光标出现在input 内容的 后面
    e.target.append(input);
    //双击时  显示input 框
    input.style.display = "block";

    input.value.innerHTML = e.target;
    //获得焦点事件
    input.focus();
    //给input 绑定键盘按键抬起事件  判断按下的是不是回车键
    input.addEventListener("keyup", function (ele) {
      console.log(input);
      if (ele.key === "Enter") {
        eventFunc();
        //解绑事件
        //removeEventListener  移除事件监听
        input.removeEventListener("blur", eventFunc);
      }
    });
    //失去焦点事件
    input.addEventListener("blur", eventFunc);
    async function eventFunc() {
      const { id, batch } = e.target.dataset;
      const result = await axios({
        url: "/score/entry",
        method: "post",
        data: {
          stu_id: id,
          batch,
          score: input.value,
        },
      });
      if (result.data.code === 0) {
        toastr.success("修改成功");
        getScore();
      }
    }
  }
});
